<?php


namespace App\Http\Rest\Admin\Resource;

use App\Http\Rest\Admin\DbResource;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Response\ResponseGen;

class RolePermission
{
    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function getList(array $restParams, ServerRequest $request)
    {
        return call_user_func([DbResource::class, 'getList'], $restParams, $request);
    }

    public function getInfo(array $restParams, ServerRequest $request)
    {
        return call_user_func([DbResource::class, 'getInfo'], $restParams, $request);
    }


    public function add(array $restParams, ServerRequest $request)
    {
        return call_user_func([DbResource::class, 'add'], $restParams, $request);
    }

    /**
     * @param array $restParams
     * @param $request ServerRequest
     */
    public function edit(array $restParams, $request)
    {
        $selectedIds = $request->getIn('selected_ids');
        if (is_null($selectedIds)) {
            return call_user_func([DbResource::class, 'edit'], $restParams, $request);
        }

        FDB::delete($restParams['resource'])->where($restParams['field'], $restParams['id'])->execute();

        if (empty($selectedIds)) {
            return ResponseGen::success();
        }
        $newRoles = [];
        foreach ($selectedIds as $id) {
            $data = [];
            if ($restParams['field'] == 'permission_id') {
                $data['permission_id'] = $restParams['id'];
                $data['role_id'] = $id;
            } else {
                $data['role_id'] = $restParams['id'];
                $data['permission_id'] = $id;
            }
            $data['assignment_date'] = date('Y-m-d H:i:s');
            $newRoles[] = $data;
        }

        FDB::insertInto($restParams['resource'], $newRoles)->execute();
        return ResponseGen::success();
    }


    public function delete(array $restParams, ServerRequest $request)
    {
        return call_user_func([DbResource::class, 'delete'], $restParams, $request);
    }
}
